package ChatNI;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;

public class TCPServer extends Thread {
	private ServerSocket srvsocket; 
	private ChatNI ni;  
	private int nbconnection; 
	private ArrayList<TCPReceivingFileTransfert> tcprcvr;


	/**
	 * Initialize the attributes 
	 * @param ChatNI Network du ChatSystem
	 */
	public TCPServer(ChatNI ni) {
		this.ni = ni;
		this.nbconnection = 0;
		tcprcvr = new ArrayList<TCPReceivingFileTransfert>();
	}

	public void run() {
		try {
			System.out.println("TCPServer : run :Creating socket");
			this.srvsocket = new ServerSocket(ChatNI.porttcp);
			System.out.println("TCPServer : run : Waiting for connection");
			//accept the connection if there is not currently already 10 connection
			if (nbconnection < 11) {
				try {
					Socket socket = srvsocket.accept();
					nbconnection++;
					TCPReceivingFileTransfert tcpreceiver = new TCPReceivingFileTransfert(socket, this, nbconnection-1);
					tcprcvr.add(tcpreceiver);
					tcpreceiver.start();
				} catch (SocketException e) {
					closeAllConnections();
					System.out.println("Socket closed, thread interrupted");
					this.interrupt();	
				}

			} else {
				System.out.println("TCPServer:run:Trop de connections!!");
			}


		} catch (IOException e) {   		
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Could not create the server socket");
		}

	}

	/**
	 * Close all the TCPReceivingFileTransfert connection
	 */
	private void closeAllConnections(){
		for (TCPReceivingFileTransfert tcp : tcprcvr){
			tcp.setRunning(false);
		}
	}

	/**
	 * Close a TCPReceivingFileTransfert connection
	 * @param ID id of the connection
	 */
	public void closeConnection(int ID) {
		System.out.println("Close Connection : " + ID);
		TCPReceivingFileTransfert rcvr = tcprcvr.get(ID);
		rcvr.setRunning(false);
		tcprcvr.remove(ID);
		nbconnection--;
	}

	/**
	 * @return the nbconnection
	 */
	public int getNbconnection() {
		return nbconnection;
	}

	/**
	 *@return the ni
	 */
	public ChatNI getNI() {
		return ni;
	}

	/**
	 *@return if the socket is close or not
	 */
	public boolean isSocketClose(){
		return srvsocket.isClosed();
	}

	/**
	 *@return the serversocket 
	 */
	public ServerSocket getServerSocket() {
		return srvsocket;
	}

	/**
	 * @param nbconnection the nbconnection to set
	 */
	public void setNbconnection(int nbconnection) {
		this.nbconnection = nbconnection;
	}
}
